<template>
  <Header />
  <div class="cart-view">
    <!-- 头部信息 -->
    <div class="header">
      <h1>我的购物车</h1>
      <div class="stats">全部商品 {{totalItems}}</div>
    </div>
    <!-- 登录提示 -->
    <div v-if="!isLoggedIn && !cartLoading" class="login-prompt">
      <div class="login-icon">🔒</div>
      <div class="login-text">请先登录以查看购物车</div>
      <router-link to="/login" class="login-btn">登录</router-link>
    </div>
    <!-- 加载状态 -->
    <div v-if="cartLoading && isLoggedIn" class="loading">
      <div class="spinner"></div>
      加载中...
    </div>
    <!-- 错误状态 -->
    <div v-else-if="error && isLoggedIn" class="error-message">
      <div class="error-icon">⚠️</div>
      <div class="error-text">{{errorMessage}}</div>
      <button class="retry-btn" @click="fetchCartItems">重试</button>
    </div>
    <!-- 空购物车状态 -->
    <div v-else-if="cartItems.length === 0 && isLoggedIn" class="empty-cart">
      <div class="empty-icon">🛒</div>
      <div class="empty-text">购物车是空的，快去选购商品吧！</div>
      <router-link to="/products" class="go-shopping">去购物</router-link>
    </div>
    <!-- 购物车商品列表 -->
    <template v-else>
      <div class="cart-controls">
        <div class="select-all">
          <input type="checkbox" id="select-all" v-model="selectAll">
          <label for="select-all">全选</label>
        </div>
        <div class="headers">
          <span class="header-product">商品</span>
          <span class="header-price">单价</span>
          <span class="header-quantity">数量</span>
          <span class="header-total">总价</span>
          <span class="header-actions">操作</span>
        </div>
      </div>
      <div class="cart-item" v-for="item in cartItems" :key="item.cartId">
        <div class="item-select">
          <input type="checkbox" :id="'item-' + item.cartId" v-model="item.selected">
        </div>
        <div class="item-image">
          <img :src="item.productImg || '/src/assets/product-default.png'" :alt="item.productName">
        </div>
        <div class="item-details">
          <div class="item-name">{{item.productName}}</div>
          <div class="item-variant">{{item.specification || '默认规格'}}</div>
          <div class="item-status">
            <span class="in-stock">有货</span>
          </div>
        </div>
        <div class="item-price">
          <div class="current-price">¥{{item.sellingPrice.toFixed(2)}}</div>
        </div>
        <div class="item-quantity">
          <div class="quantity-control">
            <button class="decrease" @click="updateQuantity(item, -1)" :disabled="item.quantity <= 1">
              -
            </button>
            <input type="number"
                   v-model.number="item.quantity"
                   class="quantity-input"
                   @change="validateQuantity(item)"
                   min="1">
            <button class="increase" @click="updateQuantity(item, 1)">+</button>
          </div>
        </div>
        <div class="item-total">
          ¥{{(item.sellingPrice * item.quantity).toFixed(2)}}
        </div>
        <div class="item-actions">
          <button class="checkout-btn" @click="checkoutItem(item)">结算</button>
          <button class="delete" @click="removeItem(item)">删除</button>
        </div>
      </div>
      <!-- 底部结算栏 -->
      <div class="cart-footer">
        <div class="footer-controls">
          <div class="select-all-footer">
            <input type="checkbox" id="select-all-footer" v-model="selectAll">
            <label for="select-all-footer">全选</label>
          </div>
          <button class="delete-selected" @click="deleteSelected" :disabled="selectedCount === 0">
            删除选中的商品
          </button>
        </div>
        <div class="checkout-section">
          <div class="selected-info">
            已选择 <span class="count">{{selectedCount}}</span> 件商品
          </div>
          <div class="total-price">
            总价：<span class="price">￥{{totalPrice.toFixed(2)}}</span>
          </div>
          <button class="checkout-btn" @click="checkout" :disabled="selectedCount === 0">
            去结算
          </button>
        </div>
      </div>
    </template>
  </div>
</template>

<script>
import request from '../../utils/request';
import Header from '../Header.vue';
import { getCartProducts, updateCartQuantity, deleteCartItem } from '@/api/cart';
import { useStore } from 'vuex';
import { computed, onMounted, ref } from 'vue';
import { useRouter } from 'vue-router';

export default {
  name: 'CartView',
  components: {
    Header
  },
  setup() {
    const store = useStore();
    const router = useRouter();
    
    const cartItems = computed(() => store.state.cartItems);
    const cartLoading = computed(() => store.state.cartLoading);
    const currentUser = computed(() => store.state.currentUser);
    const error = ref(false);
    const errorMessage = ref('');
    
    const isLoggedIn = computed(() => currentUser.value !== null);
    const selectAll = computed({
      get() {
        return cartItems.value.length > 0 && cartItems.value.every(item => item.selected);
      },
      set(value) {
        cartItems.value.forEach(item => {
          item.selected = value;
        });
      }
    });
    const selectedCount = computed(() => cartItems.value.filter(item => item.selected).length);
    const totalItems = computed(() => cartItems.value.length);
    const totalPrice = computed(() => {
      return cartItems.value.reduce((total, item) => {
        if (item.selected) {
          return total + (item.sellingPrice * item.quantity);
        }
        return total;
      }, 0);
    });
    
    const getErrorMessage = (error) => {
      if (error.response) {
        console.log('错误响应详情:', error.response);
        return `请求失败，状态码: ${error.response.status}, 信息: ${error.response.data?.message || error.response.data || '未知错误'}`;
      } else if (error.request) {
        return '请求已发送，但没有收到响应';
      } else {
        return '请求发生错误: ' + error.message;
      }
    };
    
    const fetchCartItems = async () => {
      if (!isLoggedIn.value) {
        error.value = true;
        errorMessage.value = '请先登录';
        return;
      }
      try {
        error.value = false;
        errorMessage.value = '';
        await store.dispatch('fetchCartItems');
      } catch (err) {
        console.error('获取购物车商品失败:', err);
        error.value = true;
        errorMessage.value = getErrorMessage(err);
      }
    };
    
    const updateQuantity = async (item, change) => {
      if (!isLoggedIn.value) {
        router.push('/login');
        return;
      }
      
      // 验证cartId是否存在
      if (!item.cartId) {
        console.error('cartId为空，无法更新数量:', item);
        alert('商品信息不完整，请刷新页面重试');
        return;
      }
      
      try {
        if (isNaN(item.quantity)) {
          item.quantity = 1;
        }
        let newQuantity = Math.floor(item.quantity) + change;
        newQuantity = Math.max(1, newQuantity);

        const response = await updateCartQuantity(
          currentUser.value.userId,
          item.cartId,
          newQuantity
        );

        if (response.status === 'success') {
          // 更新store中的数量
          store.commit('updateCartItemQuantity', {
            cartId: item.cartId,
            quantity: newQuantity
          });
          console.log('数量更新成功，新数量:', newQuantity);
        } else {
          throw new Error(response.message || '更新数量失败');
        }
      } catch (err) {
        console.error('更新数量失败:', err);
        
        let errorMsg = '更新数量失败';

        if (err.response) {
          const errorData = err.response.data;
          if (errorData.message) {
            errorMsg = errorData.message;
            if (errorData.message.includes('无效的商品数量')) {
              errorMsg = '商品数量必须大于0';
            } else if (errorData.message.includes('权限不足') ||
                errorData.message.includes('访问被拒绝')) {
              errorMsg = '您没有权限操作此商品';
            }
          } else if (errorData) {
            errorMsg = typeof errorData === 'string' ? errorData : JSON.stringify(errorData);
          }
        } else if (err.request) {
          errorMsg = '请求已发送，但没有收到响应';
        } else {
          errorMsg = '更新数量时发生错误: ' + err.message;
        }

        alert(errorMsg);
        // 重新获取购物车数据以确保数据同步
        fetchCartItems();
      }
    };
    
    const validateQuantity = (item) => {
      if (isNaN(item.quantity) || item.quantity < 1) {
        item.quantity = 1;
      } else {
        item.quantity = Math.floor(item.quantity);
      }
      updateQuantity(item, 0);
    };
    
    const deleteSelected = async () => {
      const selectedItems = cartItems.value.filter(item => item.selected);
      if (selectedItems.length === 0) {
        alert('请先选择要删除的商品');
        return;
      }
      if (!confirm(`确定要删除选中的${selectedItems.length}件商品吗？`)) return;
      try {
        await Promise.all(selectedItems.map(item =>
            deleteCartItem(currentUser.value.userId, item.cartId)
        ));
        
        // 从store中移除选中的商品
        selectedItems.forEach(item => {
          store.commit('removeCartItem', item.cartId);
        });
      } catch (err) {
        console.error('删除选中商品失败:', err);
        alert('删除选中商品失败');
      }
    };
    
    const checkoutItem = (item) => {
      router.push({
        name: 'Checkout',
        query: { items: [item.cartId] }
      });
    };
    
    const checkout = () => {
      if (selectedCount.value === 0) {
        alert('请选择要结算的商品');
        return;
      }
      router.push({
        name: 'Checkout',
        query: {
          items: cartItems.value
              .filter(item => item.selected)
              .map(item => item.cartId)
        }
      });
    };
    
    const removeItem = async (item) => {
      if (!confirm('确定要删除该商品吗？')) return;
      try {
        await deleteCartItem(currentUser.value.userId, item.cartId);
        // 从store中移除商品
        store.commit('removeCartItem', item.cartId);
      } catch (err) {
        console.error('删除商品失败:', err);
        alert('删除商品失败');
      }
    };
    
    onMounted(() => {
      if (currentUser.value) {
        store.dispatch('fetchCartItems');
      }
    });
    
    return {
      cartItems,
      cartLoading,
      currentUser,
      error,
      errorMessage,
      isLoggedIn,
      selectAll,
      selectedCount,
      totalItems,
      totalPrice,
      fetchCartItems,
      updateQuantity,
      validateQuantity,
      deleteSelected,
      checkoutItem,
      checkout,
      removeItem
    };
  }
};
</script>


<style scoped>
/* 新增登录提示样式 */
.login-prompt {
  padding: 2rem;
  text-align: center;
  background-color: #f0f8ff;
  border-radius: 8px;
  margin: 1rem 0;
}

.login-icon {
  font-size: 2rem;
  margin-bottom: 1rem;
  color: #1890ff;
}

.login-text {
  font-size: 1rem;
  color: #333;
  margin-bottom: 1.5rem;
}

.login-btn {
  display: inline-block;
  padding: 0.5rem 1.5rem;
  background-color: #1890ff;
  color: white;
  text-decoration: none;
  border-radius: 4px;
  transition: background-color 0.3s;
}

.login-btn:hover {
  background-color: #096dd9;
}

/* 其他样式保持不变，仅添加按钮禁用状态样式 */
button:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

/* 原购物车组件样式 */
.cart-view {
  max-width: 1200px;
  margin: 0 auto;
  padding: 2rem;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.header {
  display: flex;
  align-items: center;
  margin-bottom: 1.5rem;
}

.header h1 {
  font-size: 1.8rem;
  font-weight: 600;
  color: #333;
  margin: 0;
}

.stats {
  margin-left: 1rem;
  font-size: 1rem;
  color: #666;
}

.price-drop-notice {
  background-color: #fff8e6;
  padding: 0.75rem 1rem;
  margin-bottom: 1rem;
  border-radius: 4px;
  font-size: 0.9rem;
}

.highlight {
  color: #f5222d;
  font-weight: 500;
}

.delivery-info {
  padding: 0.75rem 0;
  font-size: 0.9rem;
  color: #666;
  margin-bottom: 1.5rem;
}

.location {
  color: #333;
  font-weight: 500;
}

.loading {
  padding: 2rem;
  text-align: center;
  color: #666;
  font-size: 1rem;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.spinner {
  border: 3px solid #f3f3f3;
  border-top: 3px solid #f5222d;
  border-radius: 50%;
  width: 30px;
  height: 30px;
  animation: spin 1s linear infinite;
  margin-bottom: 1rem;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.error-message {
  padding: 2rem;
  text-align: center;
  background-color: #fff1f0;
  border-radius: 8px;
  margin: 1rem 0;
}

.error-icon {
  font-size: 2rem;
  margin-bottom: 1rem;
}

.error-text {
  color: #f5222d;
  margin-bottom: 1rem;
}

.retry-btn {
  padding: 0.5rem 1.5rem;
  background-color: #f5222d;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.empty-cart {
  text-align: center;
  padding: 3rem;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.empty-icon {
  font-size: 3rem;
  margin-bottom: 1rem;
}

.empty-text {
  font-size: 1rem;
  color: #666;
  margin-bottom: 1.5rem;
}

.go-shopping {
  display: inline-block;
  padding: 0.5rem 1.5rem;
  background-color: #f5222d;
  color: white;
  text-decoration: none;
  border-radius: 4px;
  transition: background-color 0.3s;
}

.go-shopping:hover {
  background-color: #d32029;
}

.cart-controls {
  background-color: white;
  padding: 1rem;
  display: flex;
  align-items: center;
  border-radius: 8px 8px 0 0;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
}

.select-all {
  display: flex;
  align-items: center;
  margin-right: 1.5rem;
}

.select-all input {
  margin-right: 0.5rem;
}

.headers {
  display: flex;
  flex: 1;
  font-size: 0.9rem;
  color: #666;
}

.header-product {
  flex: 3;
}

.header-price,
.header-quantity,
.header-total {
  flex: 1;
  text-align: center;
}

.header-actions {
  flex: 1;
  text-align: center;
}

.cart-item {
  display: flex;
  padding: 1rem;
  background-color: white;
  align-items: center;
  border-bottom: 1px solid #eee;
  transition: background-color 0.3s;
}

.cart-item:hover {
  background-color: #f9f9f9;
}

.item-select {
  margin-right: 1rem;
}

.item-image {
  width: 80px;
  height: 80px;
  margin-right: 1.5rem;
}

.item-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 4px;
}

.item-details {
  flex: 3;
}

.item-name {
  font-size: 1rem;
  color: #333;
  margin-bottom: 0.5rem;
  font-weight: 500;
}

.item-variant {
  font-size: 0.85rem;
  color: #999;
  margin-bottom: 1rem;
}

.item-status {
  font-size: 0.85rem;
}

.in-stock {
  color: #1890ff;
  margin-right: 1rem;
}

.move-to-wishlist {
  color: #666;
  cursor: pointer;
  transition: color 0.3s;
}

.move-to-wishlist:hover {
  color: #f5222d;
}

.item-price,
.item-quantity,
.item-total {
  flex: 1;
  text-align: center;
}

.current-price {
  color: #f5222d;
  font-weight: 600;
  margin-bottom: 0.5rem;
}

.price-drop {
  font-size: 0.8rem;
  color: #999;
}

.saved {
  color: #f5222d;
}

.quantity-control {
  display: flex;
  justify-content: center;
  margin-bottom: 0.5rem;
}

.quantity-control button {
  width: 28px;
  height: 28px;
  border: 1px solid #ddd;
  background-color: #fff;
  cursor: pointer;
  font-size: 1rem;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: background-color 0.3s;
}

.quantity-control button:hover {
  background-color: #f5f5f5;
}

.quantity-input {
  width: 50px;
  height: 28px;
  text-align: center;
  border: 1px solid #ddd;
  margin: 0 0.25rem;
  font-size: 0.9rem;
}

.purchase-limit {
  font-size: 0.8rem;
  color: #999;
}

.item-total {
  font-weight: 600;
  color: #f5222d;
}

.item-actions {
  flex: 1;
  text-align: center;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.checkout-btn {
  padding: 6px;
  background-color: #f5222d;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

.delete {
  padding: 6px;
  background-color: #f5f5f5;
  border: 1px solid #ddd;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

.cart-footer {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: white;
  padding: 1rem;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
  display: flex;
  justify-content: space-between;
  max-width: 1200px;
  margin: 0 auto;
}

.footer-controls {
  display: flex;
  align-items: center;
}

.select-all-footer {
  display: flex;
  align-items: center;
  margin-right: 1.5rem;
}

.delete-selected,
.move-to-wishlist,
.clear-cart {
  margin-right: 0.75rem;
  padding: 0.5rem 1rem;
  border: 1px solid #ddd;
  background-color: #fff;
  cursor: pointer;
  font-size: 0.9rem;
  border-radius: 4px;
  transition: background-color 0.3s;
}

.delete-selected:hover,
.move-to-wishlist:hover,
.clear-cart:hover {
  background-color: #f5f5f5;
}

.checkout-section {
  display: flex;
  align-items: center;
}

.selected-info {
  margin-right: 1.5rem;
  font-size: 0.9rem;
}

.count {
  color: #f5222d;
  font-weight: 600;
}

.total-price {
  margin-right: 1.5rem;
  font-size: 1rem;
  font-weight: 600;
}

.price {
  color: #f5222d;
}

.checkout-btn {
  padding: 0.75rem 2rem;
  background-color: #f5222d;
  color: white;
  border: none;
  border-radius: 4px;
  font-size: 1rem;
  font-weight: 500;
  cursor: pointer;
  transition: background-color 0.3s;
}

.checkout-btn:hover {
  background-color: #d32029;
}

@media (max-width: 768px) {
  .cart-view {
    padding: 1rem;
    padding-bottom: 120px;
  }

  .cart-item {
    flex-wrap: wrap;
    padding: 0.75rem;
  }

  .item-details {
    flex: 1 0 60%;
    margin-bottom: 0.5rem;
  }

  .item-price,
  .item-quantity,
  .item-total,
  .item-actions {
    flex: 1 0 25%;
    margin-top: 0.5rem;
  }

  .cart-footer {
    flex-direction: column;
    padding: 0.75rem;
  }

  .footer-controls {
    margin-bottom: 0.75rem;
    flex-wrap: wrap;
  }

  .checkout-section {
    width: 100%;
    justify-content: space-between;
  }

  .selected-info,
  .total-price {
    margin-right: 0;
  }
}
</style>